//
//  FFMoneyPlayManager.m
//  LLWallet
//
//  Created by tt on 2020/12/23.
//

#import "FFMoneyPlayManager.h"
#import <WuKongBase/WuKongBase.h>
#import "FFWalletConst.h"
#import "FFRecvPayPaySuccessVC.h"
static FFMoneyPlayManager *_instance = nil;

@interface FFMoneyPlayManager ()<WKCMDManagerDelegate>

@end

@implementation FFMoneyPlayManager

+(instancetype)allocWithZone:(struct _NSZone *)zone{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [super allocWithZone:zone ];
    });
    return _instance;
}

+(instancetype) shared{
    if (_instance == nil) {
        _instance = [[super alloc]init];
    }
    return _instance;
}

- (void)ff_startListener {
    [[WKSDK shared].cmdManager addDelegate:self];
}

- (void)dealloc
{
    [[WKSDK shared].cmdManager removeDelegate:self];
}

- (void)play:(NSString *)money {
    NSArray *fileNameArray = [self getMusicArrayWithNum:money];
    
    /************************合成音频并播放*****************************/
    NSMutableArray* audioAssetArray = [[NSMutableArray alloc] init];
    NSMutableArray* durationArray = [[NSMutableArray alloc] init];
    [durationArray addObject:@(0)];

    AVMutableComposition* composition = [AVMutableComposition composition];

    CMTime allTime = kCMTimeZero;

    for (NSInteger i = 0; i < fileNameArray.count; i++) {
        NSString* auidoPath = [[[WKModuleManager shared] getModuleWithId:@"LLWallet"] pathForResource:[NSString stringWithFormat:@"Sound/%@",fileNameArray[i]] ofType:@"mp3"];

        AVURLAsset* audioAsset = [AVURLAsset assetWithURL:[NSURL fileURLWithPath:auidoPath]];
        [audioAssetArray addObject:audioAsset];

        // 音频轨道
        AVMutableCompositionTrack* audioTrack = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:0];

        // 音频素材轨道
        AVAssetTrack* audioAssetTrack = [[audioAsset tracksWithMediaType:AVMediaTypeAudio] firstObject];

        // 音频合并 - 插入音轨文件
        [audioTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, audioAsset.duration) ofTrack:audioAssetTrack atTime:allTime error:nil];

        // 更新当前的位置
        allTime = CMTimeAdd(allTime, audioAsset.duration);
    }

    // 合并后的文件导出 - `presetName`要和之后的`session.outputFileType`相对应。
    AVAssetExportSession* session = [[AVAssetExportSession alloc] initWithAsset:composition presetName:AVAssetExportPresetAppleM4A];
    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString* dir = [paths objectAtIndex:0];
    NSString* outPutFilePath = [dir stringByAppendingPathComponent:@"pay_money_tmp.m4a"];

    if ([[NSFileManager defaultManager] fileExistsAtPath:outPutFilePath]) {
        [[NSFileManager defaultManager] removeItemAtPath:outPutFilePath error:nil];
    }

    // 查看当前session支持的fileType类型
    NSLog(@"---%@", [session supportedFileTypes]);
    session.outputURL = [NSURL fileURLWithPath:outPutFilePath];
    session.outputFileType = AVFileTypeAppleM4A; //与上述的`present`相对应
    session.shouldOptimizeForNetworkUse = YES; //优化网络

    [session exportAsynchronouslyWithCompletionHandler:^{

        NSLog(@"%@", [NSThread currentThread]);

        if (session.status == AVAssetExportSessionStatusCompleted) {
            NSLog(@"合并成功----%@", outPutFilePath);

            NSURL* url = [NSURL fileURLWithPath:outPutFilePath];

            static SystemSoundID soundID = 0;

            AudioServicesCreateSystemSoundID((__bridge CFURLRef _Nonnull)(url), &soundID);

            if (@available(iOS 9.0, *)) {
                AudioServicesPlayAlertSoundWithCompletion(soundID, ^{
                    NSLog(@"播放完成");
                    AudioServicesDisposeSystemSoundID(soundID);
                });
            }

        } else {
            // 其他情况, 具体请看这里`AVAssetExportSessionStatus`.
        }

    }];
}

-(NSArray *)getMusicArrayWithNum:(NSString *)numStr {
    NSString *finalStr = [self parseMoney:numStr];
    NSMutableArray *finalArr = [[NSMutableArray alloc] initWithObjects:@"money",@"pay_success", nil];
    for (int i=0; i<finalStr.length; i++) {
        [finalArr addObject:[finalStr substringWithRange:NSMakeRange(i, 1)]];
    }
    return finalArr;
}

-(NSString*) parseMoney:(NSString*)numstr {
    NSArray *numberchar = @[@"0",@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9"];
    NSArray *inunitchar = @[@"",@"十",@"百",@"千"];
    NSArray *unitname   = @[@"",@"万",@"亿"];
        
    NSString *valstr =[NSString stringWithFormat:@"%.2f",numstr.doubleValue] ;
    NSString *prefix = @"" ;
    
    // 将金额分为整数部分和小数部分
    NSString *head = [valstr substringToIndex:valstr.length - 2 - 1] ;
    NSString *foot = [valstr substringFromIndex:valstr.length - 2] ;
    // 处理整数部分
    if([head isEqualToString:@"0"]) {
        prefix = @"0" ;
    }else{
        NSMutableArray *ch = [[NSMutableArray alloc]init] ;
        for (int i = 0; i < head.length; i++) {
            NSString * str = [NSString stringWithFormat:@"%x",[head characterAtIndex:i]-'0'] ;
            [ch addObject:str] ;
        }
        
        int zeronum = 0 ;
        for (int i = 0; i < ch.count; i++) {
            NSInteger index = (ch.count-1 - i)%4 ;       //取段内位置（三个数组）
            NSInteger indexloc = (ch.count-1 - i)/4 ;    //取段位置（三个数组）
            
            if ([[ch objectAtIndex:i]isEqualToString:@"0"]) {
                zeronum ++ ;
            }
            else {
                if (zeronum != 0) {
                    if (index != 3) {
                        prefix=[prefix stringByAppendingString:@"零"];
                    }
                    zeronum = 0;
                }
                if (ch.count >i) {
                    NSInteger numIndex = [[ch objectAtIndex:i]intValue];
                    if (numberchar.count >numIndex) {
                        prefix = [prefix stringByAppendingString:[numberchar objectAtIndex:numIndex]] ;
                    }
                }
                
                if (inunitchar.count >index) {
                    prefix = [prefix stringByAppendingString:[inunitchar objectAtIndex:index]] ;
                }

            }
            if (index == 0 && zeronum < 4) {
                if (unitname.count >indexloc) {
                    prefix = [prefix stringByAppendingString:[unitname objectAtIndex:indexloc]] ;

                }
            }
        }
    }
    
    //1十开头的改为十
    if([prefix hasPrefix:@"1十"]) {
        prefix = [prefix stringByReplacingOccurrencesOfString:@"1十" withString:@"十"] ;
    }
    
    //处理小数部分
    if([foot isEqualToString:@"00"]) {
        prefix = [prefix stringByAppendingString:@"元"] ;
    }
    else {
        prefix = [prefix stringByAppendingString:[NSString stringWithFormat:@"点%@元", foot]] ;
    }
    return prefix ;
    
}

#pragma mark -- LIMCMDManagerDelegate

- (void)cmdManager:(WKCMDManager *)manager onCMD:(WKCMDModel *)model {
    if([model.cmd isEqualToString:LIMCMD_RECEIVE_MONEY_SUCCESS]) { // 收款成功
        [self play:model.param[@"amount"]];
    }else if([model.cmd isEqualToString:LIMCMD_PAY_MONEY_SUCCESS]) { // 付款成功
        FFRecvPayPaySuccessVC *vc = [FFRecvPayPaySuccessVC new];
        vc.uid = model.param[@"uid"]?:@"";
        vc.amount = [WKMoneyUtil yuan2Penny:@([model.param[@"amount"] floatValue])].integerValue;
        [[WKNavigationManager shared] pushViewController:vc animated:YES];
    }
}


@end
